// import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_community/stores/counter.dart';
import 'package:flutter_community/utils/eventBus.dart';
import 'package:flutter_community/utils/http.dart';
import 'package:flutter_community/utils/preference.dart';
import 'package:provider/provider.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.currentIndex});
  //定义一个默认索引
  int currentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  //定义一个tabbar的默认下标数据
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];
//定义个人信息响应数据
  Map userInfo = {
    'id': '',
    'avatar': '',
    'nickName': '',
  };
  //组价重新构建被调用
  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    // print('组件重新构建被调用,${widget.currentIndex}');
    if (widget.currentIndex == 1) {
      getInfo();
    }
  }

  getInfo() async {
    // 获取个人信息
    final res = await http.get('/userInfo');
    setState(() {
      userInfo = res['data'];
    });
    // print(res);
  }

//token失效后重新登录调用个人信息接口
  @override
  void initState() {
    super.initState();
    eventBus.on<UserInfoRefreshEvent>().listen((data) {
      getInfo();
    });
    //接收修改后的数据
    eventBus.on<EditInfoRefreshEvent>().listen((data) {
      getInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    //使用全局数据
    final counter = Provider.of<CounterModel>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '我的${counter.counter}',
          style: const TextStyle(color: Colors.white),
        ),
        backgroundColor: const Color.fromRGBO(122, 167, 192, 1),
        centerTitle: true,
      ),
      body: Container(
        color: const Color.fromRGBO(122, 167, 192, 1),
        padding: const EdgeInsets.all(10),
        //头部标题
        child: ListView(
          children: [
            //顶部个人信息部分
            Container(
              padding: const EdgeInsets.all(10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  //左侧头像和用户名
                  Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(30),
                        child: userInfo['avatar'] == ''
                            ? Image.asset(
                                'assets/images/avatar_1.jpg',
                                width: 60,
                                height: 60,
                              )
                            : Image.network(
                                userInfo['avatar'],
                                width: 60,
                                height: 60,
                              ),
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Text(
                          userInfo['nickName'] == ''
                              ? '用户名'
                              : userInfo['nickName'],
                          style: const TextStyle(color: Colors.white))
                    ],
                  ),
                  //右侧去完善信息
                  GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, '/profile',
                          arguments: userInfo);
                    },
                    child: const Text(
                      '去完善信息 >',
                      style: TextStyle(color: Colors.white),
                    ),
                  )
                ],
              ),
            ),
            //底部卡片部分
            Container(
              margin: const EdgeInsets.only(top: 30, left: 10, right: 10),
              height: 160,
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(10)),
              child: Column(
                children: menuList.map((item) {
                  return SizedBox(
                      height: 45,
                      //左边图文,右边图标
                      child: GestureDetector(
                        onTap: () {
                          if (item['title'] == '我的房屋') {
                            Navigator.pushNamed(context, '/houseList');
                          }
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Image.asset(
                                  item['icon'],
                                  width: 20,
                                ),
                                const SizedBox(width: 10),
                                Text(item['title'])
                              ],
                            ),
                            const Icon(
                              Icons.arrow_forward_ios,
                              size: 12,
                              color: Colors.grey,
                            )
                          ],
                        ),
                      ));
                }).toList(),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            ElevatedButton(
                onPressed: () async {
                  //添加token
                  await TokenManager().saveToken('121212121');
                },
                child: const Text('添加token')),
            const SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () async {
                  //删除token
                  await TokenManager().removeToken();
                },
                child: const Text('删除token')),
            const SizedBox(
              height: 10,
            ),
            ElevatedButton(
                onPressed: () async {
                  //测试token过期
                  final res = await http.get('/room');
                  print(res);
                },
                child: const Text('获取过期token')),
            const SizedBox(height: 10),
            ElevatedButton(
                onPressed: () async {
                  counter.increment();
                },
                child: const Text('共享数据累加')),
          ],
        ),
      ),
    );
  }
}
